package com.example.shutdown_v1.schedule;

import com.example.shutdown_v1.repository.SensorDataRepository;
import com.example.shutdown_v1.repository.SwitchStateRecordRepository;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;

/**
 * 数据清理定时任务
 * 定期清理MySQL历史数据，防止数据库膨胀
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class DataCleanupScheduler {

    private final SensorDataRepository sensorDataRepository;
    private final SwitchStateRecordRepository stateRecordRepository;
    
    @Value("${data.cleanup.sensor-data-retention-days:7}")
    private int sensorDataRetentionDays;
    
    @Value("${data.cleanup.state-record-retention-days:30}")
    private int stateRecordRetentionDays;
    
    @Value("${data.cleanup.enabled:true}")
    private boolean cleanupEnabled;

    /**
     * 清理MySQL中的传感器历史数据
     * 默认每天凌晨2点执行
     */
    @Scheduled(cron = "${schedule.data-cleanup.cron:0 0 2 * * ?}")
    @Transactional
    public void cleanupOldSensorData() {
        if (!cleanupEnabled) {
            log.debug("[数据清理] 清理功能已禁用，跳过执行");
            return;
        }
        
        log.info("========== 开始清理MySQL历史传感器数据 ==========");
        
        try {
            LocalDateTime cutoffTime = LocalDateTime.now().minusDays(sensorDataRetentionDays);
            
            // 先统计待删除数据量
            long countToDelete = sensorDataRepository.countByReceiveTimeBefore(cutoffTime);
            
            if (countToDelete == 0) {
                log.info("[数据清理] 无需清理，所有数据都在保留期内");
                return;
            }
            
            // 执行删除
            int deletedCount = sensorDataRepository.deleteByReceiveTimeBefore(cutoffTime);
            
            log.info("========== 传感器数据清理完成 ==========");
            log.info("清理截止时间: {} ({} 天前)", cutoffTime, sensorDataRetentionDays);
            log.info("删除记录数: {}", deletedCount);
            log.info("剩余记录数: {}", sensorDataRepository.count());
            
        } catch (Exception e) {
            log.error("[数据清理] 传感器数据清理失败", e);
        }
    }
    
    /**
     * 清理状态变化记录（保留期更长）
     * 默认每天凌晨2:30执行
     */
    @Scheduled(cron = "${schedule.data-cleanup.state-record-cron:0 30 2 * * ?}")
    @Transactional
    public void cleanupOldStateRecords() {
        if (!cleanupEnabled) {
            return;
        }
        
        log.info("========== 开始清理历史状态记录 ==========");
        
        try {
            LocalDateTime cutoffTime = LocalDateTime.now().minusDays(stateRecordRetentionDays);
            
            // 统计待删除数据
            long countToDelete = stateRecordRepository.countByRecordTimeBefore(cutoffTime);
            
            if (countToDelete == 0) {
                log.info("[数据清理] 状态记录无需清理");
                return;
            }
            
            // 执行删除
            int deletedCount = stateRecordRepository.deleteByRecordTimeBefore(cutoffTime);
            
            log.info("========== 状态记录清理完成 ==========");
            log.info("清理截止时间: {} ({} 天前)", cutoffTime, stateRecordRetentionDays);
            log.info("删除记录数: {}", deletedCount);
            
        } catch (Exception e) {
            log.error("[数据清理] 状态记录清理失败", e);
        }
    }
    
    /**
     * 手动触发清理（用于测试或紧急清理）
     * 可通过API调用
     */
    @Transactional
    public void manualCleanup() {
        log.info("[手动清理] 开始执行...");
        cleanupOldSensorData();
        cleanupOldStateRecords();
        log.info("[手动清理] 完成");
    }
}

